//
//  Style1ViewController.m
//  PiPiPineapple
//
//  Created by 李晓东 on 17/11/7.
//  Copyright © 2017年 PeanutXu. All rights reserved.
//

#import "Style1ViewController.h"
#import "DoubleChromosphere_Extension.h"
#import "Style1TableViewDataSource.h"
#import "SQLiteManager.h"
#import "ThroadToServer.h"
#import "Tools.h"
#import "UIBarButtonItem+Category.h"
#import "LiTableView.h"

#import <Masonry.h>

@interface Style1ViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) LiTableView *tableView;
@property (nonatomic, strong) Style1TableViewDataSource *dataSource;


/**
 结果 array
 */
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@property (nonatomic, strong) ResultOfDoubleChromosphere refreshBlock;

@property (nonatomic, strong) PullUpDoubleChromsphereBlock pullUpBlock;

@end

//#define CRow 20

@implementation Style1ViewController

- (void)loadView{
    [super loadView];
    
    __weak typeof(self) weakSelf = self;
    self.refreshBlock = ^(NSArray *array){
        
        DoubleChromosphere *lastestObj = (DoubleChromosphere *)array.lastObject;
        
        if (((DoubleChromosphere *)self.array.firstObject).returnIssueno.integerValue < lastestObj.returnIssueno.integerValue){
            NSInteger difference = lastestObj.returnIssueno.integerValue - ((DoubleChromosphere *)self.array.firstObject).returnIssueno.integerValue;
            if (difference > 1) {
                [weakSelf loadFromNetWithIssueno:((DoubleChromosphere *)weakSelf.array).returnIssueno number:difference - 1 andInsertArray:array inMethod:History];
                return ;
            }
            dispatch_sync(dispatch_get_main_queue(), ^{
                [weakSelf insertDataInArray:array orDictionary:nil intoTable:@"" atIndexOf:0];
                [weakSelf insertData:array haveIndexSet:0];
            });
            
            
        } else {
            [self.tableView finishLoading];
        }
        
    };
    
    self.pullUpBlock = ^(NSArray *resultArray){
        DoubleChromosphere *obj = (DoubleChromosphere *)weakSelf.array.lastObject;
        
        [weakSelf loadFromDataBase:obj.returnIssueno andCount:CRow andParameter:@"expect" andOperate:@" < " andOrder:@"expect"];
    };
    
    self.tableView = [[LiTableView alloc]initWithBlock:self.refreshBlock andPullUpBlock:self.pullUpBlock];
    [self.view addSubview:self.tableView];
    
    self.array = [NSMutableArray array];
    self.dataSource = [[Style1TableViewDataSource alloc]initWithData:self.array];
    
    [self loadFromDataBase:nil andCount:CRow andParameter:nil andOperate:nil andOrder:@"expect"];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.dataSource = _dataSource;
    self.tableView.delegate = self;
    
    UINib *nib = [UINib nibWithNibName:@"Style1TableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"li"];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top);
        make.left.mas_equalTo(self.view.mas_left);
        make.width.mas_equalTo(self.view.mas_width);
        make.height.mas_equalTo(self.view.mas_height);
    }];
    
    // 上拉 UI
    _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [_indicatorView setColor:[UIColor redColor]];
    self.tableView.tableFooterView = _indicatorView;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"说明" style: UIBarButtonItemStylePlain target:self action:@selector(explain:) index:1];
    
    
}

/**
 从网络中加载期数,并判断是 History 还是 query. 如果是 history 就插入到结果 array 以及数据库中.如果是 query, 则调用 queryMehotdResult 方法,让它处理

 @param issueno 期数
 @param number 要查询的条数
 @param array 要把结果插入到那个 array 中
 @param method 网络请求方法, history/query
 */
- (void)loadFromNetWithIssueno:(NSString *)issueno number:(NSInteger)number andInsertArray:(NSArray *)array inMethod:(NSString *)method{
    [[[ThroadToServer shareThroadToServer] initWithParams:^(NSArray *resultArray){
        
        if ([method isEqualToString:History]) {
            
            NSArray *tempArray = [array arrayByAddingObjectsFromArray:resultArray];
            // 这里的 resultArray 是从网络加载下来的全新数据,数据库还没存在的数据
            [self insertDataInArray:resultArray orDictionary:nil intoTable:@"" atIndexOf:-1];
            // array 是已经把 resultArray 合并到刚才的查询结果中的了(不涉及数据库操作)
            [self insertData:tempArray haveIndexSet:-1];
        } else {
            [self queryMethodResult:resultArray];
            
        }
        
        [self.tableView reloadData];
    }] loadDoubleChromosphereOfType:method withIssueno:issueno ofNumber:number];
    
}

- (void)queryMethodResult:(NSArray *)resultArray{
    NSInteger netIssueno = [((DoubleChromosphere *)resultArray.lastObject).returnIssueno integerValue];
    NSInteger currentIssueno = [((DoubleChromosphere *)self.array.firstObject).returnIssueno integerValue];
    if (netIssueno > currentIssueno) {
        [self insertDataInArray:resultArray orDictionary:nil intoTable:@"" atIndexOf:0];

        if ((netIssueno - currentIssueno) > 1) {
            [self loadFromNetWithIssueno:[NSString stringWithFormat:@"%ld", netIssueno] number:(netIssueno - currentIssueno) - 1 andInsertArray:resultArray inMethod:History];
            return;
        }
        //  插入到结果 array
        [self insertData:resultArray haveIndexSet:0];
        
    }
}

/**
 从数据库中加载数据

 */
- (void)loadFromDataBase:(NSString *)issueno andCount:(NSInteger)count andParameter:(NSString *)param andOperate:(NSString *)operate andOrder:(NSString *)order {
    
    // 第一次进入到这个 UI, 会先从数据库加载数据.当发现没有数据时,会向网络请求(获取多条记录).返回的结果集会被记录到数据库,以及加载 array, 并刷新 tableViewcell; 但当数据库有数据时,也会向网络请求(获取一条最新记录),然后和数据库最新的记录比较,记录下相差的期数diff.如果diff=0,则数据库有最新的,放弃这条记录,把记过加载到 array, 并刷新 tableView;否则则保存这条记录,再判断是否大于1.大于1的话,就在访问网络(获取多条记录),把再访问网络返回的记录加载刚才的查询结果中,再把值加载给 array 和记录到数据库,再刷新 tableView;
    
    // 再完成第一次加载后.上拉刷新时,需要取出当前 tableView中最后一条记录.以该记录为条件,先从数据库加载数据.如果数据库中没有记录,则以刚才去到的记录的期数为条件,向网络请求(获取多条记录),返回的结果记录到数据库,以及加载 array, 并刷新 tableView.如果数据库中有记录,则把返回的记录加载到 array 中,并判断返回的记录数是否达到 CRow 条.如果没有达到,则向网络请求(获取多条记录),返回结果集会记录到数据库,以及加载 array, 并刷新 tableVIewCell .如果已经达到,则只刷新 tableViewcell
    
    
    RetuenBlock returnBlock = ^(NSArray *array1, BOOL needRefresh){
        // 1.1如果存在,就从中加载,并判断是否是最新的期数
        if (array1.count == 0) {
            [self loadFromNetWithIssueno:issueno number:CRow andInsertArray:array1 inMethod:History];
            
        } else {
            if (array1.count == CRow) {
                [self insertData:array1 haveIndexSet:-1];
            } else {
                
                NSString *issueno = ((DoubleChromosphere *)array1.lastObject).returnIssueno;
                
                [self loadFromNetWithIssueno:issueno number:CRow - array1.count andInsertArray:array1 inMethod:History];
            }
   
        }
    };
    
    [[SQLiteManager share]queryDataInTable:@"T_DoubleChromosphere" andReturnBlock:returnBlock andOrderBy:order andSort:@"desc" andResultCount:CRow withParameter:param andOperate:operate andValue:issueno, nil];

}


/**
 把数据插入到数据库中, array 和 dictionary 哪个需要插入那个对象才有值,不可能同时有值的

 @param array 要插入数据库的 DoubleChromosphere类型数组
 @param dictionary DoubleChromosphere字典
 @param tableName 表明
 @param index XXX
 */
- (void)insertDataInArray:(NSArray *)array orDictionary:(NSDictionary *)dictionary intoTable:(NSString *)tableName atIndexOf:(NSInteger)index{
    [[SQLiteManager share]insertDataOfArray:array orDictionary:dictionary inTable:@"T_DoubleChromosphere"];
    
}

- (void)insertData:(NSArray *)array haveIndexSet:(NSInteger)indexOfIndexSet {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (array != nil) {
            if (self.tableView.state == loading) {
                self.tableView.state = idle;
            }
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(indexOfIndexSet < 0 ? MAX(self.array.count, 0) : indexOfIndexSet, array.count)];
            [self.array insertObjects:array atIndexes:indexSet];
            
            dispatch_sync(dispatch_get_global_queue(0, 0), ^{
                for (NSInteger i = array.count; i > 1; i--) {
                    NSArray *allRedArray = ((DoubleChromosphere *)array[i - 2]).returnRedBall;
                    NSString *blueBallStr = ((DoubleChromosphere *)array[i - 1]).returnBlueBall;
                    if ([allRedArray containsObject:blueBallStr]) {
                        [((DoubleChromosphere *)array[i - 2]) setNextSomeBody:blueBallStr];
                        
                    }
                    
                }
            });
            
        }
        [self.indicatorView stopAnimating];
        [self.tableView reloadData];
    });
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    [self removeObserver:self.tableView forKeyPath:@"contentOffset"];
}

@end
